package it.tukano.treditor.modules;

import it.tukano.check.Todo;
import it.tukano.fun.StartsWith;
import it.tukano.lang.StringExt;
import it.tukano.log.Log;
import it.tukano.reflection.CallMap;
import java.net.URL;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.event.HyperlinkListener;

/**
 * This is used to handle hyperlinks in the html display of the HelpSystemModule
 */
public class DefaultHelpSystemHyperlinkListener implements HyperlinkListener {
    
    private final CallMap linkEventCallMap = new CallMap()
            .add(EventType.ACTIVATED, this, "linkActivated", HyperlinkEvent.class);
    private final CallMap urlHandlerCallMap = new CallMap()
            .add(new StartsWith("help:"), this, "jumpToHelpPage", String.class);
    private final HelpSystemModule context;

    /**
     * Instance initializer
     */
    public DefaultHelpSystemHyperlinkListener(HelpSystemModule context) {
        this.context = context;        
    }

    public void hyperlinkUpdate(HyperlinkEvent e) {
        linkEventCallMap.call(e.getEventType(), e);
    }
    
    public void linkActivated(HyperlinkEvent e) {
        String description = e.getDescription();
        URL url = e.getURL();
        String address = url == null ? description : url.toString();
        urlHandlerCallMap.call(address, address);
    }
    
    public void jumpToHelpPage(String url) {
        String page = StringExt.wrap(url).removePrefix("help:").toString();
        context.loadPageFromDefaultBase(page);
    }
}
